/*
Copyright (C) 2016  Marien Raat

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "carAI.h"
#include "config.h"

#include <SFML/Graphics.hpp>
#include <Box2D/Box2D.h>
#include <cmath>
#include <iostream>

CarAI::CarAI()
{
    secondsNotMoving = 0.0f;
    movingBackTime = 0.0f;
}

void CarAI::setBall(Ball *ball)
{
    this->ball = ball;
}

void CarAI::setCar(Car *car)
{
    this->car = car;
}

void CarAI::update()
{
    b2Vec2 linearVelocity = car->getBody()->GetLinearVelocity();
    float angularVelocity = car->getBody()->GetAngularVelocity();

    float linearThreshold = 0.001f,
        angularThreshold = 40.0f;
    bool notMoving = (linearVelocity.x < linearThreshold &&
                      linearVelocity.y < linearThreshold &&
                      angularVelocity < angularThreshold);
    if (notMoving) secondsNotMoving += timeStep;
    else secondsNotMoving = 0.0f;

    bool stuck = secondsNotMoving > 1.0f;

    if (stuck && movingBackTime <= 0.0f) {
        movingBackTime = 1.0f;
    }

    if (movingBackTime > 0.0f) {
        car->power = -1;

        car->turning = getTurning(car->getRotation() - 90.0f);

        movingBackTime -= timeStep;
    } else {
        car->power = 1;

        car->turning = getTurning(car->getRotation() + 180);
    }

    previousPosition = car->getPosition();
}

float CarAI::getTurning(float myRotation)
{
    sf::Vector2f myPosition = car->getPosition();
    sf::Vector2f ballPosition = ball->getPosition();
    sf::Vector2f distance = myPosition - ballPosition;

#define MAP_TO_0_360(x)                         \
    ((std::fmod((x), 360) < 0) ?                \
     (360 + std::fmod((x), 360))                \
     : std::fmod((x), 360))
    float myRotationMapped = MAP_TO_0_360(myRotation);
    float targetRotation = MAP_TO_0_360(
        atan2(distance.y, distance.x) * RAD_TO_DEG);

    float rotationDifference = targetRotation - myRotationMapped;
    float turnChange;
    if (fabs(rotationDifference) <= 180.0f)
        turnChange = rotationDifference;
    else
        turnChange = -rotationDifference;

    return copysign(
        std::min(1.0f, (float) fabs(turnChange)), turnChange);

}
